package com.wdl.report.business.pp.mvp.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;
import com.wdl.report.R;
import com.wdl.report.R2;
import com.wdl.report.app.utils.ChartUtils;
import com.wdl.report.app.utils.CodeUtils;
import com.wdl.report.business.pp.di.component.DaggerReportPpComponent;
import com.wdl.report.business.pp.mvp.contract.ReportPpContract;
import com.wdl.report.business.pp.mvp.presenter.ReportPpPresenter;
import com.wdl.report.db.ReportInfo;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTouch;
import me.wdl.component.commonsdk.core.RouterHub;
import me.wdl.component.commonsdk.utils.Utils;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 02/15/2019 21:55
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@Route(path = RouterHub.REPORT_PPACTIVITY)
public class ReportPpActivity extends BaseActivity<ReportPpPresenter> implements ReportPpContract.View {

    @BindView(R2.id.support_print_view)
    ScrollView print_view;

    @BindView(R2.id.pp_linechart_qjxq)
    LineChart chart_qjxq;
    @BindView(R2.id.pp_linechart_kjjciia)
    LineChart chart_kja;
    @BindView(R2.id.pp_linechart_kjjciib)
    LineChart chart_kjb;
    @BindView(R2.id.pp_linechart_mjjc)
    LineChart chart_mj;
    @BindView(R2.id.pp_linechart_nljc)
    LineChart chart_nl;
    @BindView(R2.id.pp_linechart_hjxqjc)
    LineChart chart_hjxq;

    @BindView(R2.id.qjxq_zdssl)
    TextView qjxq_zdssl;
    @BindView(R2.id.kja_sspjz)
    TextView kja_sspjz;
    @BindView(R2.id.kja_jldj)
    TextView kja_jldj;
    @BindView(R2.id.kja_pld)
    TextView kja_pld;
    @BindView(R2.id.kjb_sspjz)
    TextView kjb_sspjz;
    @BindView(R2.id.kjb_jldj)
    TextView kjb_jldj;
    @BindView(R2.id.kjb_pld)
    TextView kjb_pld;
    @BindView(R2.id.mj_sspjz)
    TextView mj_sspjz;
    @BindView(R2.id.mj_sjldj)
    TextView mj_sjldj;
    @BindView(R2.id.mj_pld)
    TextView mj_pld;
    @BindView(R2.id.nl_sszdz)
    TextView nl_sszdz;
    @BindView(R2.id.nl_sspjz)
    TextView nl_sspjz;
    @BindView(R2.id.nl_sscxsj)
    TextView nl_sscxsj;
    @BindView(R2.id.hjxq_zdssl)
    TextView hjxq_zdssl;

    @BindView(R2.id.title_reprot)
    EditText et_title;

    @BindView(R2.id.pp_page_01)
    LinearLayout page_01;

    @BindView(R2.id.pp_page_02)
    LinearLayout page_02;

    @BindView(R2.id.input_name)
    EditText et_name;

    @BindView(R2.id.input_sex)
    EditText et_sex;

    @BindView(R2.id.input_age)
    EditText et_age;


    private LoadingDialog loadingDialog;
    private RxPermissions rxPermissions;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerReportPpComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_report_pp; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        rxPermissions = new RxPermissions(this);

        ChartUtils.initChart(chart_qjxq);
        ChartUtils.initChart(chart_kja);
        ChartUtils.initChart(chart_kjb);
        ChartUtils.initChart(chart_mj);
        ChartUtils.initChart(chart_nl);
        ChartUtils.initChart(chart_hjxq);

        String reprotTitle = RxSPTool.getString(this, TITLE_SP);
        if (reprotTitle == null || reprotTitle.length() == 0)
            showEditTitleDialog(this);
        else
            et_title.setText(reprotTitle);

        showAjust();

        mPresenter.initReceiveListener();
    }

    @Override
    public void showLoading() {
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("努力操作中...");

        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        if (loadingDialog != null)
            loadingDialog.close();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @OnClick(R2.id.print_upload)
    public void clickUpload() {
        showOrHideAjustCursor(false);

        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
//                        mPresenter.upload(ReportPpActivity.this, print_view);
                        mPresenter.upload(ReportPpActivity.this, page_01, page_02);
                    } else {
                        RxToast.error("存储权限异常");
                    }
                });

        saveAjust();
    }

    @OnClick(R2.id.print_receive)
    public void clickReceive() {
        clearChart();

        havingReceive = true;

        mPresenter.startReceiveCmd();
    }


    @OnClick(R2.id.search_setting)
    public void clickSearch() {
        Utils.navigation(this, RouterHub.REPORT_SEARCHACTIVITY);
    }


    @OnClick(R2.id.print_dyj)
    public void clickPrint() {
//        int d=1/0;

        showOrHideAjustCursor(false);

        mPresenter.print(this, page_01, page_02);

        saveAjust();
    }

    @OnClick(R2.id.print_change)
    public void clickChange() {
        showChooseModel(this);
    }

    @OnClick(R2.id.print_setting)
    public void clickSetting() {
        showEditTitleDialog(this);
    }

    @Override
    public void uploadSuccess(String url) {
        MaterialDialog show = new MaterialDialog.Builder(ReportPpActivity.this)
                .customView(R.layout.dialog_show_code, true)
                .show();

        CodeUtils.showErCode(show.getCustomView().findViewById(R.id.img_ercode), url);
    }

    @Override
    public void showQjxq(List<Entry> entries) {
        showChartData(chart_qjxq, entries);
    }

    @Override
    public void showKjjca(List<Entry> entries) {
        showChartData(chart_kja, entries);
    }

    @Override
    public void showKjjcb(List<Entry> entries) {
        showChartData(chart_kjb, entries);
    }

    @Override
    public void showMjjc(List<Entry> entries) {
        showChartData(chart_mj, entries);
    }

    @Override
    public void showNljc(List<Entry> entries) {
        showChartData(chart_nl, entries);
    }

    @Override
    public void showHjxq(List<Entry> entries) {
        showChartData(chart_hjxq, entries);
    }

    @Override
    public void showTotalData(List<Integer> datas) {
        runOnUiThread(() -> {
            qjxq_zdssl.setText(String.format("%smmHg", getIntStr(datas, 0)));
            kja_sspjz.setText(String.format("%smmHg", getIntStr(datas, 1)));
            kja_jldj.setText(String.format("%s级", getIntStr(datas, 2)));
            kja_pld.setText(String.format("%s%%", getIntStr(datas, 3)));
            kjb_sspjz.setText(String.format("%smmHg", getIntStr(datas, 4)));
            kjb_jldj.setText(String.format("%s级", getIntStr(datas, 5)));
            kjb_pld.setText(String.format("%s%%", getIntStr(datas, 6)));
            mj_sspjz.setText(String.format("%smmHg", getIntStr(datas, 7)));
            mj_sjldj.setText(String.format("%s级", getIntStr(datas, 8)));
            mj_pld.setText(String.format("%s%%", getIntStr(datas, 9)));
            nl_sszdz.setText(String.format("%smmHg", getIntStr(datas, 10)));
            nl_sspjz.setText(String.format("%smmHg", getIntStr(datas, 11)));
            nl_sscxsj.setText(String.format("%s秒", getIntStr(datas, 12)));
            hjxq_zdssl.setText(String.format("%smmHg", getIntStr(datas, 13)));
        });
    }

    private String getIntStr(List<Integer> datas, int postion) {
        if (datas == null || postion >= datas.size()) {
            return "-";
        }

        return String.valueOf(datas.get(postion));
    }

    @Override
    public ReportInfo getWrapReportInfo() {
        ReportInfo reportInfo = new ReportInfo();
        reportInfo.setReportType(1);
        reportInfo.setName(et_name.getText().toString().trim());
        reportInfo.setSex(et_sex.getText().toString().trim());
        reportInfo.setAge(et_age.getText().toString().trim());
        reportInfo.setReportTime(new Date());
        return reportInfo;
    }

    private boolean havingReceive = false;

    private void clearChart() {
        ChartUtils.resetLinechart(chart_qjxq);
        ChartUtils.resetLinechart(chart_kja);
        ChartUtils.resetLinechart(chart_kjb);
        ChartUtils.resetLinechart(chart_mj);
        ChartUtils.resetLinechart(chart_nl);
        ChartUtils.resetLinechart(chart_hjxq);
    }

    private void showChartData(LineChart lineChart, List<Entry> entries) {
        runOnUiThread(() -> ChartUtils.addLineFillData(lineChart, entries));
    }

    private String[] stocks = {"PP", "PPA", "PPV"};

    private void showChooseModel(Activity context) {
        MaterialDialog.Builder mBuilder = new MaterialDialog.Builder(context);
        mBuilder.title("选择模式");
        mBuilder.titleGravity(GravityEnum.CENTER);
        mBuilder.titleColor(Color.parseColor("#000000"));
        mBuilder.items(stocks);
        mBuilder.autoDismiss(true);
        mBuilder.itemsCallback((dialog, itemView, position, text) -> {
            if ("PP".equals(text)) {
//                Utils.navigation(ReportPpActivity.this, RouterHub.REPORT_PPACTIVITY);
            } else if ("PPA".equals(text)) {
                Utils.navigation(context, RouterHub.REPORT_PPAACTIVITY);
//                Utils.navigation(context, RouterHub.REPORT_SEARCHACTIVITY);
                clearChart();
            } else if ("PPV".equals(text)) {
                Utils.navigation(context, RouterHub.REPORT_PPVACTIVITY);
                clearChart();
            }
        });
        MaterialDialog mMaterialDialog = mBuilder.build();
        mMaterialDialog.show();
    }

    private static final String TITLE_SP = "pp_report";


    @BindView(R2.id.input_ajust)
    EditText et_ajust;

    @BindView(R2.id.input_date)
    EditText et_date;

    private void showOrHideAjustCursor(boolean show) {
        et_ajust.setCursorVisible(show);
        et_age.setCursorVisible(show);
        et_name.setCursorVisible(show);
        et_sex.setCursorVisible(show);
        et_date.setCursorVisible(show);
    }

    @OnTouch({R2.id.input_ajust, R2.id.input_name, R2.id.input_sex, R2.id.input_age, R2.id.input_date})
    public boolean onTouch(View v, MotionEvent event) {
        if (MotionEvent.ACTION_DOWN == event.getAction()) {
            showOrHideAjustCursor(true);// 再次点击显示光标
        }
        return false;
    }

    private static final String AJUST_SP = "pp_report_ajust";

    private void saveAjust() {
        String trim = et_ajust.getText().toString().trim();
        if (trim != null && trim.length() > 0) {
            RxSPTool.putString(this, AJUST_SP, trim);
        }
    }

    private void showAjust() {
        String string = RxSPTool.getString(this, AJUST_SP);
        if (string != null && string.length() > 0) {
            et_ajust.setText(string);
        }
    }

    private void showEditTitleDialog(Activity context) {
        new MaterialDialog.Builder(context)
                .title("请自主输入报告标题")
                .inputType(InputType.TYPE_CLASS_TEXT)
                .input("标题", null, (dialog, input) -> {
                    String title = input.toString();
                    if (title != null && title.length() > 0) {
                        et_title.setText(title);
                        RxSPTool.putString(context, TITLE_SP, title);
                    }
                })
                .positiveText("确定")
                .show();
    }

}
